/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ceair.flight.refund.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author Colin_You
 */
@Service
public class MultiTaskRunner implements IMultiTaskRunner {

    private static final Logger LOG = LoggerFactory.getLogger(MultiTaskRunner.class);

    @Override
    public <T> List<Future<T>> runTasks(List<Callable<T>> tasks) {
        ExecutorService executorService = Executors.newFixedThreadPool(8);
        try {
            List copyTasks = new ArrayList<>(tasks);
            List<Future<T>> result = executorService.invokeAll(copyTasks, 90, TimeUnit.SECONDS);
            executorService.shutdown();
            executorService.awaitTermination(30, TimeUnit.SECONDS);
            return result;
        } catch (InterruptedException ex) {
            executorService.shutdown();
            LOG.error("Tasks run in background error", ex);
        }
        return null;
    }

}
